<template>
    <div class="wrap normal">
        <el-row :gutter="20">
            <el-col :span="5">
                <!-- 搜索条件 -->
                <div class="tree-form">
                    <el-input v-model="form.deptName" placeholder="请输入部门名称" clearable style="width: 220px">
                        <i class="el-icon-search el-input__icon" slot="suffix" @click="pageOperate('searchDept')"> </i>
                    </el-input>
                </div>
                <div class="tree-content">
                    <el-tree ref="treeList" :data="deptTreeList" :props="deptTreeProps" :default-expand-all="false" :default-expanded-keys="expandedKeys" highlight-current :expand-on-click-node="false" node-key="id" @node-click="searchTreeNodeClick">
                        <span class="custom-tree-node" slot-scope="{ node }">{{ node.label }}</span>
                    </el-tree>
                </div>
            </el-col>
            <el-col :span="19">
                <!-- 搜索条件 -->
                <div class="wrap-form" id="wrap-form">
                    <div class="left-panel">
                        <el-form :inline="true" :model="form" label-width="60px" @submit.native.prevent>
                            <el-form-item>
                                <el-input v-model="form.userName" placeholder="输入账号搜索" clearable style="width: 220px"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" icon="el-icon-search" @click="pageOperate('search')">搜索</el-button>
                                <el-button type="primary" icon="el-icon-plus" v-hasPerm="'system:userManage:add'" @click="pageOperate('add')">添加</el-button>
                                <el-button icon="el-icon-refresh" @click="pageOperate('refresh')">刷新</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
                <!-- table数据 -->
                <div class="wrap-table">
                    <el-table ref="singleTable" :data="tableData" :max-height="tableMaxHeight" border v-loading="tableLoading" :header-cell-style="{ background: '#F5F6FA' }">
                        <el-table-column type="index" label="序号" width="50" align="center"> </el-table-column>
                        <el-table-column prop="companyName" label="公司名称" min-width="180"> </el-table-column>
                        <el-table-column prop="deptName" label="部门" min-width="120"> </el-table-column>
                        <el-table-column label="头像" min-width="100">
                            <template slot-scope="scope">
                                <el-image style="width: 40px; height: 40px; border-radius: 50%; cursor: pointer" :src="scope.row.avatarUrl" fit="fill" :preview-src-list="[scope.row.avatarUrl]"></el-image>
                            </template>
                        </el-table-column>
                        <el-table-column prop="mobile" label="手机号" min-width="120"> </el-table-column>
                        <el-table-column label="角色" min-width="140">
                            <template slot-scope="scope">
                                {{ scope.row.roleNames && scope.row.roleNames.length > 0 ? scope.row.roleNames.join(',') : '' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="创建时间" min-width="140">
                            <template slot-scope="scope">
                                {{ scope.row.createTime | iso8601DateTimeFormat }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="状态" min-width="100">
                            <template slot-scope="scope">
                                <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" @change="changeUserStatus($event, scope.row.id)"> </el-switch>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="100" fixed="right">
                            <template slot-scope="scope">
                                <el-button type="text" v-hasPerm="'system:userManage:edit'" @click="pageOperate('edit', scope.row)">修改</el-button>
                                <el-button type="text" v-hasPerm="'system:userManage:delete'" @click="pageOperate('deleteOne', scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination :total="page.totalNum" :page.sync="page.pageNum" :limit.sync="page.pageSize" layout="total, sizes, prev, pager, next, jumper" @pagination="getTableData" />
                </div>
            </el-col>
        </el-row>
        <!-- 新增/编辑用户 -->
        <el-dialog v-if="operateDialog" :title="operateTitle" :visible.sync="operateDialog" @close="closeOperateDialog" :width="`${operateWidth}px`" :close-on-press-escape="false" :close-on-click-modal="false">
            <el-form ref="operateForm" :model="operateForm" :rules="operateRules" label-width="80px">
                <el-form-item label="头像" class="avatar-item" v-if="operateType === 'add' || operateType === 'edit'">
                    <el-upload ref="upload" :action="domain" :data="qiniuData" :multiple="false" :show-file-list="false" :limit="1" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
                        <el-avatar icon="el-icon-user-solid" :size="48" :src="operateForm.avatarUrl"></el-avatar>
                    </el-upload>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="operateForm.mobile" clearable placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="部门" prop="deptName">
                    <el-select ref="treeOptionsSelect" v-model="operateForm.deptName" placeholder="请选择部门" :popper-append-to-body="false" style="width: 100%">
                        <el-option :value="operateForm.deptId" style="height: 100%">
                            <el-tree :data="deptOptions" :props="deptOptionsProps" default-expand-all :expand-on-click-node="false" node-key="value" @node-click="operateFormTreeNodeClick">
                                <span class="custom-tree-node" :class="data.value === operateForm.deptId ? 'checked' : ''" slot-scope="{ node, data }">{{ node.label }}</span>
                            </el-tree>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="角色" prop="roleId">
                    <el-select v-model="operateForm.roleId" placeholder="请选择角色" clearable style="width: 100%">
                        <el-option v-for="(item, index) in roleOptions" :label="item.label" :value="item.value" :key="index" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeOperateDialog">取 消</el-button>
                <el-button type="primary" :loading="operateLoading" @click="operateSubmit">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getUserManageList, addOrUpdateUser, updateUserStatus, deleteUser, getRolePermsOptions, getDepartList, getDepartTree } from '@/api/system'
import { getQiNiuToken } from '@/api/common'
import { genderOptions } from '@/filters/options'
import tableHeight from '@/mixins/tableHeight'
import { domain, qiniuUrl } from '@/config/request'
export default {
    name: 'UserManage',
    mixins: [tableHeight],
    data() {
        return {
            form: {
                // 搜索内容
                content: '',
                // 部门树搜索
                deptName: '',
                // 部门选中搜索
                deptId: ''
            },
            page: {
                pageNum: 1,
                pageSize: 10,
                totalNum: 0
            },
            tableData: [],
            tableLoading: false,
            // 操作
            operateType: '',
            operateTitle: '',
            operateWidth: 550,
            operateDialog: false,
            operateLoading: false,
            // 操作form
            operateForm: {
                // 用户id
                id: '',
                avatarUrl: '',
                mobile: '',
                // 部门
                deptName: '',
                deptId: '',
                // 角色
                roleId: '',
            },
            // 上传地址
            domain,
            // 上传参数
            qiniuData: {
                key: '',
                token: ''
            },
            // 七牛外链地址
            qiniuUrl,
            // 操作表单校验规则
            operateRules: {
                avatarUrl: [
                    { required: true, message: '请上传头像', trigger: ['blur', 'change'] }
                ],
                mobile: [
                    { required: true, message: '请输入手机号', trigger: ['blur'] }
                ],
                deptName: [
                    { required: true, message: '请选择上级部门', trigger: ['blur', 'change'] }
                ],
                roleId: [
                    { required: true, message: '请选择角色', trigger: ['blur', 'change'] }
                ]
            },
            // 角色列表 - 选择用户对应角色
            roleOptions: [],
            // 性别选项
            genderOptions,
            // 左侧部门树
            deptTreeList: [],
            // 左侧部门树属性配置
            deptTreeProps: {
                label: 'name',
                children: "children"
            },
            // 部门树选项
            deptOptions: [],
            // 部门选项属性配置
            deptOptionsProps: {
                label: 'label',
                children: "children"
            },
            // 默认展开节点
            expandedKeys: []
        }
    },
    methods: {
        // 变更用户状态
        changeUserStatus(status, id) {
            updateUserStatus({
                id: id,
                status: status
            }).then(res => { }).catch(error => { })
        },
        // 数据
        getTableData() {
            this.tableLoading = true
            const data = {
                ...this.form,
                pageNum: this.page.pageNum,
                pageSize: this.page.pageSize
            }
            getUserManageList(data).then(res => {
                this.tableLoading = false
                this.tableData = res.data.records
                this.page.totalNum = res.data.total
            }).catch(error => {
                this.tableLoading = false
            })
        },
        // 操作
        pageOperate(type, row) {
            this.operateType = type
            switch (type) {
                case 'search':
                    this.page.pageNum = 1
                    this.getTableData()
                    break;
                case 'searchDept':
                    this.initDeptTree()
                    break;
                case 'refresh':
                    this.form = this.$options.data().form
                    this.page = this.$options.data().page
                    this.tableData = []
                    this.getTableData()
                    this.deptTreeList = []
                    this.initDeptTree()
                    break;
                case 'add':
                    this.operateDialog = true
                    this.operateTitle = '新增用户'
                    this.getUploadToken()
                    if (this.deptOptions.length === 0) this.initDeptOptions()
                    if (this.roleOptions.length === 0) this.initRoleOptions()
                    break;
                case 'edit':
                    this.operateDialog = true
                    this.operateTitle = '修改用户'
                    this.getUploadToken()
                    if (this.deptOptions.length === 0) this.initDeptOptions()
                    if (this.roleOptions.length === 0) this.initRoleOptions()
                    for (let key in this.operateForm) {
                        if (key === 'roleId') {
                            this.operateForm[key] = row.roleIds[0]
                        } else {
                            this.operateForm[key] = row[key]
                        }
                    }
                    break;
                case 'deleteOne':
                    this.$confirm('确认删除此用户?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        deleteUser(row.id).then(res => {
                            this.getTableData()
                            this.$message_tip(`删除成功`, 'success')
                        }).catch(error => { })
                    }).catch(() => { });
                    break;
                default:
                    break;
            }
        },
        // 获取七牛云token
        getUploadToken() {
            getQiNiuToken().then(res => {
                this.qiniuData.token = res.data
            }).catch(error => { })
        },
        // 头像上传前
        beforeAvatarUpload(file) {
            if (!this.qiniuData.token) return this.$message_tip('上传token获取失败', 'warning')
            this.qiniuData.key = file.name
        },
        // 头像上传成功
        handleAvatarSuccess(res, file) {
            this.operateForm.avatarUrl = `${this.qiniuUrl}/${res.key}`
            this.$refs.operateForm.validateField('avatarUrl')
        },
        // 提交
        operateSubmit() {
            this.$refs.operateForm.validate(valid => {
                if (valid) {
                    if (this.operateType === 'add' || this.operateType === 'edit') {
                        this.operateLoading = true
                        let formData = JSON.parse(JSON.stringify(this.operateForm))
                        delete formData.deptName
                        formData['rolesIds'] = [formData.roleId]
                        delete formData.roleId
                        addOrUpdateUser(formData).then(res => {
                            this.getTableData()
                            this.$message_tip(`${this.operateTitle}成功`, 'success')
                            this.closeOperateDialog()
                        }).catch(error => {
                            this.operateLoading = false
                        })
                    }
                }
            })
        },
        // 关闭操作按钮
        closeOperateDialog() {
            this.operateLoading = false
            this.operateDialog = false
            this.operateTitle = ''
            this.operateType = ''
            this.operateForm = this.$options.data().operateForm
        },
        // 左侧-部门树
        initDeptTree() {
            getDepartList({
                name: this.form.deptName
            }).then(res => {
                this.deptTreeList = res.data
                // 默认展开第一项
                if (res.data && res.data.length > 0) {
                    this.expandedKeys.push(res.data[0].id)
                    this.form.deptId = res.data[0].id
                    this.$nextTick(()=>{
                        this.$refs.treeList.setCurrentKey(this.form.deptId)
                        this.getTableData()
                    });
                }
            }).catch(error => { })
        },
        // 新增-部门选项
        initDeptOptions() {
            getDepartTree({}).then(res => {
                this.deptOptions = res.data
            }).catch(error => { })
        },
        // 表单选择部门
        operateFormTreeNodeClick(data) {
            this.operateForm.deptName = data.label;
            this.operateForm.deptId = data.value
            this.$refs.treeOptionsSelect.blur()
        },
        // 角色选项
        initRoleOptions() {
            getRolePermsOptions().then(res => {
                this.roleOptions = res.data
                console.log(this.roleOptions, 'this.roleOptions');
            }).catch(error => { })
        },
        // 左侧搜索
        searchTreeNodeClick(data) {
            this.form.deptId = data.id
            this.page = this.$options.data().page
            this.tableData = []
            this.getTableData()
        },
    },
    mounted() {
        this.initDeptTree()
    },
    watch: {
        'form.deptName': function (newVal, oldVal) {
            if (oldVal && !newVal) this.initDeptTree()
        }
    }
}
</script>

<style lang="scss" scoped>
.tree-content {
    margin-top: 20px;
    ::v-deep {
        .el-tree {
            font-size: 14px;
            .el-tree-node {
                .el-tree-node__content {
                    height: 30px;
                    border-radius: 4px;
                }
            }
        }
    }
}

.el-dialog__body {
    .el-form {
        .el-select-dropdown {
            .el-select-dropdown__item {
                padding: 0 0;
            }
            .el-select-dropdown__item.selected {
                color: inherit;
                font-weight: normal;
            }
        }
    }
    .el-tree {
        .el-tree-node {
            .el-tree-node__content {
                .el-tree-node__expand-icon {
                    margin-left: 8px;
                }
                .custom-tree-node.checked {
                    color: $--color-primary;
                }
            }
        }
    }
}

::v-deep {
    .avatar-item {
        .el-form-item__content > div:nth-child(1) {
            height: 50px;
            overflow: hidden;
        }
        .el-upload {
            height: 50px;
        }
    }
}
</style>
